#include "head.h"

sqlite3 *db = NULL;  //数据库句柄

void do_login(int sockfd, MSG *pbuf)
{
	MSG msg;
	enum USER_LEVEL level;
	memset(&msg,0,sizeof(msg));

	char *errmsg;
	char **resultp;
	int n_row, n_cloum;
	int i, j;
	char cmd[128];
	
	if (sqlite3_get_table(db, "select * from admin", &resultp, &n_row, &n_cloum, &errmsg) != SQLITE_OK)
	{
		printf("err:%s\n", errmsg);
	}
	sprintf(cmd, "select * from admin where name = '%s' and pass = '%s'",pbuf->name,pbuf->passwd);
	if (sqlite3_get_table(db,cmd, &resultp, &n_row, &n_cloum, &errmsg) != SQLITE_OK)
	{
		printf("err:%s\n", errmsg);
	}
	if(n_row > 0)
	{
		strcpy(pbuf->data,"SUCCESS");
		pbuf->type = ADMIN;
		send(sockfd,pbuf, sizeof(MSG), 0);
		goto end;	
	}

	if (sqlite3_get_table(db, "select *from staff", &resultp, &n_row, &n_cloum, &errmsg) != SQLITE_OK)
	{
		printf("err:%s\n", errmsg);
	}
	sprintf(cmd, "select * from staff where name = '%s' and pass = '%s'",pbuf->name,pbuf->passwd);
	if (sqlite3_get_table(db,cmd, &resultp, &n_row, &n_cloum, &errmsg) != SQLITE_OK)
	{
		printf("err1:%s\n", errmsg);
	}
	if(n_row > 0)
	{
		puts("bb");
		strcpy(pbuf->data,"SUCCESS");
		pbuf->type = STAFF;
		send(sockfd,pbuf, sizeof(MSG), 0);	
	}
	
	end: ;
}

void do_staff_change_passwd(int sockfd, MSG *pbuf)
{
	char *errmsg;
	char cmd[256];
	MSG msg = *pbuf;
	char buf[100];

	sprintf(cmd, "update staff set pass = '%s' where name = '%s'", msg.passwd, msg.info.name);
	if(sqlite3_exec(db, cmd,  NULL,  NULL, &errmsg) !=  SQLITE_OK)
	{
		printf("error:%s\n",  errmsg);
		return;
	}else{
		puts("change password ok");
	}
}

void do_staff_query(int sockfd, MSG *pbuf)
{
	    
	char *errmsg;
	char cmd[256];
	MSG msg = *pbuf;
	char buf1[100];
	char buf2[100];
	char **resultp;
	int n_row, n_cloum;
	int j;

	sprintf(cmd, "select * from staff where name = '%s'", msg.info.name);
	sqlite3_get_table(db, cmd,&resultp, &n_row, &n_cloum, &errmsg);
	if(n_row < 1)
	{
	
		memset(buf1, 0, sizeof(buf1));
		strcpy(buf1,"query ERR\n");
		send(sockfd, buf1, sizeof(buf1), 0);
		printf("error:%s\n",  errmsg);
		return;
	}else{
		puts("query OK!");
		memset(buf1, 0, sizeof(buf1));
		
		for (j = 0; j < n_cloum; j++)
		{
			sprintf(buf2, "%s:%s\n", resultp[j], resultp[(j+n_cloum)]);
			strcat(buf1, buf2);
			memset(buf2, 0, sizeof(buf2));
			
		}
		send(sockfd, buf1, sizeof(buf1), 0);
	}
}
/*
void do_admin_query(int sockfd, MSG *pbuf)
{
    
}
*/

void do_admin_add(int sockfd, MSG *pbuf)
{
	char *errmsg;
	char cmd[256];
	MSG msg = *pbuf;
	char buf[100];
	sprintf(cmd, "insert into staff values(%d, '%s','%s', %d, '%s', %0.1f)",\
			msg.info.id, msg.info.name, msg.passwd,msg.info.age, msg.info.addr, msg.info.salary);
	printf("cmd = %s\n", cmd);

	if(sqlite3_exec(db, cmd,  NULL,  NULL, &errmsg) !=  SQLITE_OK)
	{
		strcpy(buf, "insert err");
		send(sockfd,buf, sizeof(buf), 0);
		printf("error:%s\n",  errmsg);
		return;
	}else{
		sprintf(buf, "insert OK!");
		send(sockfd,buf, sizeof(buf), 0);
	}
}

void do_admin_del(int sockfd, MSG *pbuf)
{
	char *errmsg;
	char cmd[256];
	MSG msg = *pbuf;
	char buf[100];

	sprintf(cmd, "delete from staff where name = '%s'", msg.info.name);
	printf("cmd = %s\n", cmd);
	if(sqlite3_exec(db, cmd,  NULL,  NULL, &errmsg) !=  SQLITE_OK)
	{
		sprintf(buf, "delete ERR!");
		printf("%s", buf);
		send(sockfd, buf, sizeof(buf), 0);
		printf("error:%s\n",  errmsg);
		return;
	}else{
		sprintf(buf, "delete OK!");
		printf("%s", buf);
		send(sockfd, buf, sizeof(buf), 0);
	}
}


void *handler(void * arg)
{
     MSG msg;
    int n;
    int connfd = (int)arg;

    while(1)
    {
		printf("==========server recving CMD===========\n");
        n = recv(connfd, &msg, sizeof(MSG), 0);
        //printf("name = %s\n", msg.name);
        if(n == 0){  //客户端退出
            pthread_exit(NULL);
            close(connfd);
        }else if(n > 0){  //收到信息
            //printf("recv type = %d\n", msg.type);
            switch (msg.type) {
            case LOGIN:  //登录
                do_login(connfd, &msg);
                break;
            case STAFF_CHANGE_PASSWD:
                do_staff_change_passwd(connfd, &msg);
                break;
            case STAFF_QUERY:
                do_staff_query(connfd, &msg);
                break;
//            case ADMIN_QUERY:
//                do_admin_query(connfd, &msg);
//                break;
            case ADMIN_DEL_STAFF:
                do_admin_del(connfd, &msg);
                break;
            case ADMIN_ADD_STAFF:
                do_admin_add(connfd, &msg);
                break;
           
       
            default:
                break;
            }
        }else{
            printf("abc");
            break;
        }
    }
    close(connfd);
    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    int listenfd, connfd;
    struct sockaddr_in myaddr;

    if (argc < 3)
    {
        printf("Usage : %s <ip> <port>\n", argv[0]);
        exit(-1);
    }

    //打开数据库
    if(sqlite3_open(DATABASE, &db) < 0){
        printf("fail to sqlite3_open : %s\n", sqlite3_errmsg(db));
        return -1;
    }

    //创建服务器socket
    listenfd = socket(PF_INET, SOCK_STREAM, 0);
    if(listenfd < 0){
        perror("fail to socket");
        exit(-1);
    }
    bzero(&myaddr, sizeof(myaddr));
    myaddr.sin_family = PF_INET;
    myaddr.sin_port = htons(atoi(argv[2]));
    myaddr.sin_addr.s_addr = inet_addr(argv[1]);
    if (bind(listenfd, (SA *)&myaddr, sizeof(myaddr)) < 0)
    {
        perror("fail to bind");
        exit(-1);
    }

    //  int listen(int sockfd, int backlog);
    if (listen(listenfd, 5) < 0)
    {
        perror("fail to listen");
        exit(-1);
    }

    //接受客户端请求，创建子线程
    while(1){
		printf("请连接客户端:\n");
        if((connfd = accept(listenfd, NULL, NULL)) < 0){
            perror("fail to accept");
            exit(-1);
        }
        pthread_t child_pthread;
        if(pthread_create(&child_pthread, NULL, handler,(void *)connfd) < 0)
        {
            perror("pthread_create");
            exit(1);
        }		
    }
}
